package com.ck.mq.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * TODO
 *
 * @author chenke
 * @version 1.0
 * @date 2021/8/29 12:09
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    /**
     * 实现接口方法
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 根据beanName返回相应的对象
     *
     * @param beanName
     * @return
     */
    public static <T> T getBeanByName(String beanName) {
        if (applicationContext.containsBean(beanName)) {
            return (T) applicationContext.getBean(beanName);
        } else {
            return null;
        }
    }

    /**
     * 根据bean的类型返回一个对象
     *
     * @param type
     * @return
     */
    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> baseType) {
        return applicationContext.getBeansOfType(baseType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        if (applicationContext.containsBean(name)) {
            return applicationContext.getBean(name, requiredType);
        } else {
            return null;
        }
    }
}
